import axios, {
    type InternalAxiosRequestConfig,
    type AxiosResponse,
    type AxiosRequestConfig,
  } from "axios";
import { ResultEnum } from "../enums/ResultEnum";
import { message } from 'antd';
  
  // 创建 axios 实例
  const service = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 50000,
    headers: { "Content-Type": "application/json;charset=utf-8" }
  });
  
  // 请求拦截器
  service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
      const accessToken =sessionStorage.getItem("token");

      console.log("accessToken",accessToken);
      
      // 如果 Authorization 设置为 no-auth，则不携带 Token，用于登录、刷新 Token 等接口
      if (config.headers.Authorization !== "no-auth" && accessToken) {
        config.headers.Authorization = accessToken;
      } else {
        delete config.headers.Authorization;
      }
      return config;
    },
    (error) => Promise.reject(error)
  );
  
  // 响应拦截器
  service.interceptors.response.use(
    (response: AxiosResponse) => {
      // 如果响应是二进制流，则直接返回，用于下载文件、Excel 导出等
      if (response.config.responseType === "blob") {
        return response.data;
      }
  
      const { errCode, data, errMsg,imageCode,token } = response.data;

      console.log(errCode);
      
      if (errCode === ResultEnum.SUCCESS) {

        if(imageCode){
            return {imageCode,token};
        }
        return data;
      }
  
    //   ElMessage.error(msg || "系统出错");
      message.error(errMsg ||  "系统出错");
      return Promise.reject(new Error(errMsg || "Error"));
    },
    async (error: any) => {
      const { config, response } = error;
      if (response) {
        const { code, msg } = response.data;
        if (code === ResultEnum.ACCESS_TOKEN_INVALID) {
          // Token 过期，刷新 Token
          
        } else if (code === ResultEnum.REFRESH_TOKEN_INVALID) {
          return Promise.reject(new Error(msg || "Error"));
        } else {
        //   ElMessage.error(msg || "系统出错");
        }
      }
      return Promise.reject(error.message);
    }
  );
  
  export default service;
  
  const get = <T, R>(url: string, params?: T): Promise<R> => {
    return service.get(url, { params });
  };
  const post = <T, R>(url: string, data?: T, config?: AxiosRequestConfig): Promise<R> => {
    return service.post(url, data, config);
  };
  const del = <T, R>(url: string, params?: T): Promise<R> => {
    return service.delete(url, { params });
  };
  const put = <T, R>(url: string, data?: T): Promise<R> => {
    return service.put(url, data);
  };
  export { get, post, del, put };
  
 
   